package com.edu.demo.quartz.job;

import com.edu.demo.config.OssConfig;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;

@Slf4j
@Component
public class DeleteRubbishJob implements Job {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OssConfig ossConfig;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //取出缓存
        Set headImg = redisTemplate.opsForHash().keys("headImg");
        for (Object o : headImg) {
            //获取时间戳
            Long time = (Long) redisTemplate.opsForHash().get("headImg", o);
            //判断时间戳是否超过一天
            if (System.currentTimeMillis() - time > 1000 * 60 * 60 * 24) {
                //删除oss文件
                ossConfig.deleteObject((String) o);
                //判断是否删掉
                if (! ossConfig.doesObjectExist((String) o)) {
                    //删除缓存
                    redisTemplate.opsForHash().delete("headImg", o);
                }
            }
        }
    }
}
